using JT808Protocol.Abstracts;
using JT808Protocol.Common;
using JT808Protocol.Models;
using System;

namespace JT808Protocol.Methods
{
    public class JT808Parser : IJT808Parser
    {
        public JT808Package Parse(string hexString)
        {
            Span<byte> input = ParseHelper.HexStrToBytes(hexString);
            return Parse(input);
        }

        public JT808Package Parse(ReadOnlySpan<byte> hexBytes)
        {
            var package = new JT808Package();

            if (hexBytes[0] != 0x7E || hexBytes[hexBytes.Length - 1] != 0x7E)
            {
                package.ErrMsg = "无法解析，不是完整的808协议包(缺少0x7E标识位)";
                return null;
            }

            //长度检查 7E(1)+7E(1)+校验位(1)+消息体最小长度(11)
            if (hexBytes.Length < 14) return null;

            byte[] buffer = hexBytes.ToArray();

            //还原转义
            byte[] dataEsc = ParseHelper.EscRestore(ref buffer, 0, buffer.Length);

            //验证校验码
            var checkCode = buffer[dataEsc.Length - 2];
            if (ParseHelper.CheckSum(dataEsc, 1, dataEsc.Length - 3)
                == checkCode)
            {
                package.ReadEntity(dataEsc);
                return package;
            }
            else
            {
                return null;
            }
        }
    }
}